#include "stack.h"

using namespace std;

stack::stack(int n): size(n)
{
	// new string and the size of this stack
	if(n <= 0)
		throw("The size of stack is non-positive!");
	else
		stack_array = new int[n];

	for(int i=0;i<=n-1;i++){
		stack_array[i] = 0; // empty
	}

	top_pos = -1; // position of top element
}


stack::~stack(void)
{
	delete []stack_array;
	stack_array = NULL;
}

bool stack::push(int new_ch){
	if(top_pos < size-1){
		// not full
		top_pos++;
		stack_array[top_pos] = new_ch;
		return 1;
	}else{
		// full
		return 0;
	}
}

int* stack::pop(){
	int* top_ch = NULL; // return NULL if empty
	if(top_pos >= 0){
		// non empty
		top_ch = new int;
		*top_ch = stack_array[top_pos];
		top_pos --;
	}
	return top_ch;
}

int* stack::peek()const {
	// check the top element
	int* tmp = NULL; // return NULL if empty

	if(top_pos >=0){
		// non-empty
		tmp = new int;
		*tmp = stack_array[top_pos];
	}

	return tmp;
}

ostream& operator<< (std::ostream& out, stack& st){
	// print from the top to the bottom
	if(st.top_pos < 0)
		out << " Empty stack! ";
	else{
		for(int i = st.top_pos;i>=0;i--){
			out << st.stack_array[i] << " ";
		}
	}
	return out;
}